import { ref, unref, reactive } from 'vue';

/**
 * 封装分页hook
 * @param {*} func 请求数据的 api 接口
 * @returns 
 */
export function usePager(func) {

  /** 分页参数 */
  // const pageInfo = reactive({
  //   page: 1,
  //   size: 10,
  // })

  // 分页数据设置
  const pageInfo = reactive({
    current: 1,
    pageSize: 10,
    showSizeChanger: true, //设置每页显示数据条数
    showQuickJumper: false,
    defaultPageSize: 10,
    pageSizeOptions: ['10', '15', '20', '30'],
    total: 0,
    showTotal: (total) => `共${total}条`,
    onChange: (current) => {
      pageInfo.current = current
      queryData();
    },
    onShowSizeChange: (current, pageSize) => {
      pageInfo.pageSize = pageSize
      pageInfo.current = current
      queryData();
    }
  })
  /** 返回数据及其他业务数据 */
  const resState = reactive({
    btnStatus: 1,     // 加载按钮状态 1:可继续加载 2:已经加载完了，参考@/config【BTN_STATUS】
    loading: 0,
    list: [],         // 数据列表容器
    total: 0          // 数据总量
  })

  const selectedRowKeys = ref([])
  const onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    state.selectedRowKeys = selectedRowKeys;
  };

  const rowSelection = reactive({
    selectedRowKeys: [],
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(selectedRowKeys, selectedRows);
      rowSelection.selectedRowKeys = selectedRowKeys;
    },
  })

  /**
   * 请求数据（仅获取数据方法使用）
   * @param {*} func 请求数据的方法 例：getArticleList
   * @param {*} params 其他自定义请求参数
   */
  const queryData = async (params = {}) => {
    const res = await func({ page: pageInfo.current, size: pageInfo.pageSize, ...params })
    handleQuery(res)
    return res
  }

  /**
   * 处理返回参数（仅获取数据方法使用）
   * @param {*} param0 接口请求后返回的数据 
   * @param {*} type   是否loadmore
   * @returns 
   */
  const handleQuery = ({ data, code, msg }) => {
    if (code !== 200) return;
    pageInfo.total = data.total
    resState.loading = false

    if (data.rows.length === 0 || pageInfo.size > data.rows.length) {
      resState.btnStatus = 2
    }
    resState.list = data.rows
  }

  /**
   * 加载更多
   */
  const loadingMore = (params = {}) => {
    if (resState.btnStatus !== 1) return
    pageInfo.page += 1
    queryData(params)
  }

  return {
    pageInfo,
    resState,
    rowSelection,
    queryData,
    loadingMore,
    handleQuery,
  }
}


export const useSearch = (searchFunc) => {
  let timeout;

  /** 异步节流请求数据方法 */
  function fetch(val) {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    timeout = setTimeout(() => { searchFunc(val) }, 300);
  }

  const data = ref([]);
  const value = ref();

  const handleSearch = (val) => {
    fetch(val);
  };
  const handleChange = (val) => {
    value.value = val;
    fetch(val);
  };

  return {
    data, value, handleSearch, handleChange
  }
}